import {Button} from 'antd';
import React, {Fragment} from "react";
import {findDOMNode} from 'react-dom';
import View from "../base/View";
import defaultData, { dftWaterMark } from "./data";

import SignaturePad from 'signature_pad/dist/signature_pad.js';
import classNames from 'classnames';
import './View.less';
import {WeaLocaleProvider} from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;

export default class SignatureView extends View {
  constructor(props) {
    super(props);

    this.signature = null;
    this.state = {
      isShowPad: false, // 是否显示签名面板
      hasSign: false, // 是否签名
    };
  }

  componentDidMount() {
    this.initSignaturePad();
  }

  resizeCanvas() {
    const img = findDOMNode(this.img);
    const canvasDOM = findDOMNode(this.canvas);
    const ratio = Math.max(window.devicePixelRatio || 1, 1);
    const DEFAULT_HEIGHT = 200;

    canvasDOM.width = canvasDOM.offsetWidth * ratio;
    canvasDOM.height = DEFAULT_HEIGHT * ratio;
    img.height = canvasDOM.height / ratio;
    canvasDOM.getContext("2d").scale(ratio, ratio);
  }

  initSignaturePad = () => {
    if (this.signature) return;

    const canvasDOM = findDOMNode(this.canvas);
    canvasDOM && (this.signature = new SignaturePad(canvasDOM, {
      onEnd: () => {
        this.setState({
          hasSign: true
        });
      }
    }))
  }

  showSignaturePad = () => {
    this.initSignaturePad();

    this.setState({ isShowPad: true });
    setTimeout(() => {
      this.resizeCanvas();
    });
  }

  onClear = () => {
    if(!this.state.hasSign) return;

    this.signature.backgroundColor = '#fff';
    this.signature.clear();
    this.setState({
      hasSign: false
    });
  }

  onCancel = () => {
    this.onClear();
    this.setState({
      isShowPad: false
    });
  }

  onOK = () => {
    const datas = this.signature.toData();

    this.signature.backgroundColor = '#eee';
    this.signature.fromData(datas);
    this.addMark();

    this.props.onChange(this.canvas.toDataURL());
  }

  // 添加水印
  addMark() {
    const { offsetWidth, offsetHeight } = this.canvas;
    const ctx = this.canvas.getContext('2d');
    const singleMark = this.getSingleMark();
    const pat = ctx.createPattern(singleMark, 'repeat');
    
    ctx.rect(0, 0, offsetWidth, offsetHeight);
    ctx.fillStyle = pat;
    ctx.fill();
  }

  getSingleMark() {
    const { watermark = dftWaterMark } = this.props.data;
    const canvas = document.createElement('canvas');
    const WIDTH = 160;
    const HEIGHT = 80;
    const ANGLE = -20;

    canvas.width = WIDTH;
    canvas.height = HEIGHT;

    const ctx = canvas.getContext('2d');

    ctx.font ='24px 黑体';
    ctx.rotate(ANGLE * Math.PI / 180);
    ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
    ctx.fillText(watermark.content, 0, HEIGHT / 1.2);
    ctx.rotate(-ANGLE * Math.PI / 180);

    return canvas;
  }

  onDelete = () => {
    this.props.onChange('');
    this.onClear();
    this.setState({
      isShowPad: false
    });
  }

  renderContent(data, value) {
    const { hasSign } = this.state;
    let { isShowPad } = this.state;

    const isShowSign = !!value;
    if (isShowSign && value.img) {
      isShowPad = true;
    }

    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@zp6k7t`}>
        <span>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mszzow`}
            icon='edit'
            type='ghost'
            className={classNames('wea-edc-form-btn', { hide: isShowPad })}
            onClick={this.showSignaturePad}
          >
            {getLabel('502530','点击开始签署电子签名')}
          </Button>
        </span>
        <div className={classNames('wea-edc-signature_pad', { hide: !isShowPad })}>
          <div className={classNames('signature_pad-toolbar', { hide: isShowSign })}>
            <a className={classNames({ disabled: !hasSign })} onClick={this.onClear}>{getLabel(2022,'重置')}</a>
          </div>
          <img ref={el => this.img = el} width='100%' src={value.img || value} className={classNames({ hide: !isShowSign })} />
          <canvas className={classNames({ hide: isShowSign })} ref={el => this.canvas = el} style={{ width: '100%' }}></canvas>
          <div className='signature_pad-footer clearfix'>
            {!isShowSign ?
              <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@k0m2ic`}>
                <span>{getLabel('502531','签署签名后请点击「确认签名」，系统将自动生成签名图片。')}</span>
                <div>
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m3956m`} onClick={this.onCancel}>{getLabel('502532','取消签名')}</Button>
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8ouc5i`} disabled={!hasSign} onClick={this.onOK}>{getLabel('502533','确认签名')}</Button>
                </div>
              </Fragment>
              :
              <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@2kddqf`}>
                <span>{getLabel('502534','如需重新签署签名请点击「删除签名」后，重新签署。')}</span>
                <div><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@e6yk6z`} className='signature_pad-btn-del' onClick={this.onDelete}>{getLabel('502535','删除签名')}</Button></div>
              </Fragment>
            }
          </div>
        </div>
      </Fragment>
    );
  }

  renderForReadonly(data, value) {
    if(!value) return null;
    return <img width='50' height='50' src={value.img} onClick={() => {this.showDocFile(value.link)}}/>
  }
}

SignatureView.defaultProps = {
  data: defaultData,
  value: ''
};